import React, { useState, useEffect } from 'react';
import { Table, Card, Spin, message, Badge, Button, Modal, Typography, Descriptions, Row, Col, Progress, Statistic, Space, Tooltip } from 'antd';
import { InfoCircleOutlined, ReloadOutlined, DashboardOutlined, TrophyOutlined, AlertOutlined, LineChartOutlined, PieChartOutlined, BarChartOutlined, RiseOutlined } from '@ant-design/icons';
import { $getStockRiskScores, $getStockRiskDetail } from '../../api/riskApi';
import { $getUserAssets } from '../../api/userAssetApi';
import ChatAssistant from '../ChatAssistant/ChatAssistant';

const { Text, Title } = Typography;

const RiskStock = () => {
  const [assets, setAssets] = useState([]);
  const [scores, setScores] = useState([]);
  const [loading, setLoading] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [detail, setDetail] = useState(null);
  const [overallRisk, setOverallRisk] = useState(null);

  // 计算整体风险评分的算法
  const calculateOverallRisk = (assetsWithScores) => {
    if (!assetsWithScores || assetsWithScores.length === 0) {
      return null;
    }

    const validAssets = assetsWithScores.filter(asset => asset.risk_score != null);
    if (validAssets.length === 0) {
      return null;
    }

    const totalMarketValue = validAssets.reduce((sum, asset) => {
      return sum + (asset.quantity * (asset.latest_price || asset.buy_price || 0));
    }, 0);

    if (totalMarketValue === 0) {
      return null;
    }

    const weightedRiskSum = validAssets.reduce((sum, asset) => {
      const marketValue = asset.quantity * (asset.latest_price || asset.buy_price || 0);
      const weight = marketValue / totalMarketValue;
      return sum + (asset.risk_score * weight);
    }, 0);

    const weights = validAssets.map(asset => {
      const marketValue = asset.quantity * (asset.latest_price || asset.buy_price || 0);
      return marketValue / totalMarketValue;
    });

    const hhi = weights.reduce((sum, weight) => sum + weight * weight, 0);
    const concentrationRisk = hhi;

    const avgRisk = validAssets.reduce((sum, asset) => sum + asset.risk_score, 0) / validAssets.length;
    const variance = validAssets.reduce((sum, asset) => {
      return sum + Math.pow(asset.risk_score - avgRisk, 2);
    }, 0) / validAssets.length;
    const volatilityRisk = Math.sqrt(variance);

    const finalRisk = weightedRiskSum * 0.7 + concentrationRisk * 0.2 + volatilityRisk * 0.1;

    return {
      overall: Math.min(1, Math.max(0, finalRisk)),
      weightedAverage: weightedRiskSum,
      concentration: concentrationRisk,
      volatility: volatilityRisk,
      totalAssets: validAssets.length,
      totalMarketValue: totalMarketValue
    };
  };

  const getRiskLevel = (score) => {
    if (score >= 0.8) return { level: '高风险', color: '#ff4757', bgColor: 'linear-gradient(135deg, #ff6b7a, #ff4757)', status: 'exception' };
    if (score >= 0.6) return { level: '中高风险', color: '#ffa502', bgColor: 'linear-gradient(135deg, #ffb74d, #ffa502)', status: 'active' };
    if (score >= 0.4) return { level: '中等风险', color: '#ff9f43', bgColor: 'linear-gradient(135deg, #ffcc70, #ff9f43)', status: 'normal' };
    if (score >= 0.2) return { level: '低风险', color: '#26d0ce', bgColor: 'linear-gradient(135deg, #4ecdc4, #26d0ce)', status: 'success' };
    return { level: '极低风险', color: '#3742fa', bgColor: 'linear-gradient(135deg, #70a1ff, #3742fa)', status: 'success' };
  };

  const fetchData = async () => {
    try {
      setLoading(true);
      const aRes = await $getUserAssets();
      const list = aRes.data.filter(a => a.type === '股票');
      setAssets(list);
      
      if (list.length > 0) {
        const uid = JSON.parse(localStorage.getItem('user_info')).id;
        const s = await $getStockRiskScores(uid);
        setScores(s);

        const assetsWithScores = list.map(a => {
          const f = s.find(r => r.id === a.id);
          return { ...a, risk_score: f ? f.risk_score : null };
        });

        const overallRiskData = calculateOverallRisk(assetsWithScores);
        setOverallRisk(overallRiskData);
      }
    } catch (e) {
      message.error(e.msg || '加载失败');
    } finally { 
      setLoading(false); 
    }
  };

  useEffect(() => { 
    fetchData(); 
  }, []);

  const showDetail = async id => {
    try {
      setLoading(true);
      const d = await $getStockRiskDetail(id);
      setDetail(d);
      setDetailVisible(true);
    } catch (e) {
      message.error(e.msg || '获取详情失败');
    } finally { 
      setLoading(false); 
    }
  };

  const dataSource = assets.map(a => {
    const f = scores.find(r => r.id === a.id);
    return { ...a, risk_score: f ? f.risk_score : null };
  });

  const cols = [
    { 
      title: '代码', 
      dataIndex: 'products_id', 
      key: 'products_id', 
      width: 120,
      render: (text) => <Text strong style={{ color: '#3742fa' }}>{text}</Text>
    },
    { 
      title: '名称', 
      dataIndex: 'products_name', 
      key: 'products_name', 
      width: 150,
      render: (text) => <Text>{text}</Text>
    },
    { 
      title: '市值', 
      key: 'market_value', 
      width: 120,
      render: (_, record) => {
        const mv = record.quantity * (record.latest_price || record.buy_price || 0);
        return <Text strong style={{ color: '#2ed573' }}>¥{mv.toLocaleString()}</Text>;
      }
    },
    { 
      title: '风险评分', 
      dataIndex: 'risk_score', 
      key: 'risk_score',
      width: 140,
      render: v => v != null ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <div 
            style={{
              width: '60px',
              height: '6px',
              borderRadius: '3px',
              background: v > 0.7 ? 'linear-gradient(90deg, #ff4757, #ff6b7a)' : 
                         v > 0.4 ? 'linear-gradient(90deg, #ffa502, #ffb74d)' : 
                         'linear-gradient(90deg, #26d0ce, #4ecdc4)',
              position: 'relative'
            }}
          >
            <div 
              style={{
                position: 'absolute',
                left: `${v * 100}%`,
                top: '50%',
                transform: 'translate(-50%, -50%)',
                width: '2px',
                height: '10px',
                background: '#fff',
                borderRadius: '1px',
                boxShadow: '0 1px 3px rgba(0,0,0,0.3)'
              }}
            />
          </div>
          <Text strong style={{ color: v > 0.7 ? '#ff4757' : v > 0.4 ? '#ffa502' : '#26d0ce' }}>
            {(v * 100).toFixed(1)}%
          </Text>
        </div>
      ) : <Text type="secondary">-</Text>
    },
    { 
      title: '操作', 
      key: 'op', 
      width: 100,
      render: (_, r) => (
        <Button 
          type="primary"
          ghost
          icon={<InfoCircleOutlined />} 
          size="small"
          onClick={() => showDetail(r.id)}
          style={{ 
            borderRadius: '20px',
            background: 'linear-gradient(135deg, #667eea, #764ba2)',
            border: 'none',
            color: '#fff'
          }}
        >
          详情
        </Button>
      ) 
    }
  ];

  const overallRiskInfo = overallRisk ? getRiskLevel(overallRisk.overall) : null;

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      padding: '24px'
    }}>
      <div style={{
        maxWidth: '1400px',
        margin: '0 auto'
      }}>
        {/* 头部区域 */}
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '24px'
        }}>
          <div>
            <Title level={1} style={{ 
              color: '#fff', 
              margin: 0,
              textShadow: '0 2px 4px rgba(0,0,0,0.3)',
              fontSize: '32px',
              fontWeight: '700'
            }}>
              <RiseOutlined style={{ marginRight: '12px' }} />
              股票持仓风险评估
            </Title>
            <Text style={{ color: 'rgba(255,255,255,0.8)', fontSize: '16px' }}>
              智能分析您的投资组合风险，助力科学决策
            </Text>
          </div>
          <Button 
            type="primary"
            icon={<ReloadOutlined />} 
            onClick={fetchData} 
            loading={loading}
            size="large"
            style={{
              borderRadius: '25px',
              height: '50px',
              paddingLeft: '24px',
              paddingRight: '24px',
              background: 'rgba(255,255,255,0.2)',
              border: '1px solid rgba(255,255,255,0.3)',
              backdropFilter: 'blur(10px)',
              fontSize: '16px'
            }}
          >
            刷新数据
          </Button>
        </div>

        {/* 整体风险概览卡片 */}
        {overallRisk && (
          <Card 
            style={{ 
              marginBottom: '24px',
              borderRadius: '20px',
              overflow: 'hidden',
              border: 'none',
              boxShadow: '0 20px 40px rgba(0,0,0,0.1)',
              background: 'rgba(255,255,255,0.95)',
              backdropFilter: 'blur(20px)'
            }}
            bodyStyle={{ padding: '32px' }}
          >
            <div style={{ marginBottom: '24px' }}>
              <Title level={3} style={{ 
                margin: 0, 
                color: '#2c3e50',
                display: 'flex',
                alignItems: 'center',
                gap: '12px'
              }}>
                <div style={{
                  width: '40px',
                  height: '40px',
                  borderRadius: '12px',
                  background: overallRiskInfo.bgColor,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#fff'
                }}>
                  <DashboardOutlined style={{ fontSize: '20px' }} />
                </div>
                整体风险概览
              </Title>
            </div>
            
            <Row gutter={32}>
              <Col span={6}>
                <div style={{
                  padding: '24px',
                  borderRadius: '16px',
                  background: overallRiskInfo.bgColor,
                  color: '#fff',
                  textAlign: 'center',
                  position: 'relative',
                  overflow: 'hidden'
                }}>
                  <div style={{
                    position: 'absolute',
                    top: '-20px',
                    right: '-20px',
                    width: '80px',
                    height: '80px',
                    borderRadius: '50%',
                    background: 'rgba(255,255,255,0.1)',
                    opacity: 0.5
                  }}></div>
                  <div style={{ position: 'relative', zIndex: 1 }}>
                    <div style={{ fontSize: '36px', fontWeight: 'bold', marginBottom: '8px' }}>
                      {(overallRisk.overall * 100).toFixed(1)}%
                    </div>
                    <div style={{ fontSize: '16px', opacity: 0.9 }}>综合风险评分</div>
                    <div style={{ fontSize: '14px', opacity: 0.8, marginTop: '4px' }}>
                      {overallRiskInfo.level}
                    </div>
                  </div>
                </div>
              </Col>
              
              <Col span={6}>
                  <div style={{
                   padding: '24px',
                   borderRadius: '16px',
                   background: overallRisk.weightedAverage > 0.5 ? 'linear-gradient(135deg, #ff6b7a, #ff4757)' : 'linear-gradient(135deg, #4ecdc4, #26d0ce)',
                   color: '#fff',
                   textAlign: 'center'
                  }}>
                  <div style={{ position: 'relative', zIndex: 1 }}>
                    <div style={{ fontSize: '36px', fontWeight: 'bold', marginBottom: '8px' }}>
                      {(overallRisk.weightedAverage * 100).toFixed(1)}%
                    </div>
                    <div style={{ fontSize: '16px', opacity: 0.9 }}>风险分布</div>
                    <div style={{ fontSize: '14px', opacity: 0.8, marginTop: '4px' }}>
                      {overallRiskInfo.level}
                    </div>
                  </div>
                </div>
              </Col>
              
              <Col span={6}>
                <div style={{
                  padding: '24px',
                  borderRadius: '16px',
                  background: overallRisk.concentration > 0.5 ? 'linear-gradient(135deg, #ff6b7a, #ff4757)' : 'linear-gradient(135deg, #4ecdc4, #26d0ce)',
                  color: '#fff',
                  textAlign: 'center'
                }}>
                  <PieChartOutlined style={{ fontSize: '32px', marginBottom: '8px' }} />
                  <div style={{ fontSize: '24px', fontWeight: 'bold' }}>
                    {(overallRisk.concentration * 100).toFixed(1)}%
                  </div>
                  <div style={{ fontSize: '14px', opacity: 0.9 }}>持仓集中度</div>
                  <div style={{ fontSize: '12px', opacity: 0.8, marginTop: '4px' }}>
                    {overallRisk.concentration > 0.5 ? '过度集中' : '分散良好'}
                  </div>
                </div>
              </Col>
              
              <Col span={6}>
                <div style={{
                  padding: '24px',
                  borderRadius: '16px',
                  background: overallRisk.volatility > 0.3 ? 'linear-gradient(135deg, #ffb74d, #ffa502)' : 'linear-gradient(135deg, #4ecdc4, #26d0ce)',
                  color: '#fff',
                  textAlign: 'center'
                }}>
                  <BarChartOutlined style={{ fontSize: '32px', marginBottom: '8px' }} />
                  <div style={{ fontSize: '24px', fontWeight: 'bold' }}>
                    {(overallRisk.volatility * 100).toFixed(1)}%
                  </div>
                  <div style={{ fontSize: '14px', opacity: 0.9 }}>风险波动性</div>
                  <div style={{ fontSize: '12px', opacity: 0.8, marginTop: '4px' }}>
                    {overallRisk.volatility > 0.3 ? '波动较大' : '相对稳定'}
                  </div>
                </div>
              </Col>
            </Row>
            
            <div style={{ 
              marginTop: '24px', 
              padding: '16px', 
              borderRadius: '12px', 
              background: 'rgba(103,126,234,0.1)',
              border: '1px solid rgba(103,126,234,0.2)'
            }}>
              <Text style={{ color: '#667eea', fontSize: '14px' }}>
                <strong>风险构成分析：</strong>
                加权平均风险 {(overallRisk.weightedAverage * 100).toFixed(1)}% 
                + 集中度风险 {(overallRisk.concentration * 100).toFixed(1)}% 
                + 波动性风险 {(overallRisk.volatility * 100).toFixed(1)}%
                （总持仓 {overallRisk.totalAssets} 只，总市值 ¥{overallRisk.totalMarketValue.toLocaleString()}）
              </Text>
            </div>
          </Card>
        )}

        {/* 持仓详情表格 */}
        <Card 
          title={
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              <div style={{
                width: '32px',
                height: '32px',
                borderRadius: '8px',
                background: 'linear-gradient(135deg, #667eea, #764ba2)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#fff'
              }}>
                <LineChartOutlined style={{ fontSize: '16px' }} />
              </div>
              <span style={{ fontSize: '18px', fontWeight: '600', color: '#2c3e50' }}>持仓明细</span>
            </div>
          }
          style={{
            borderRadius: '20px',
            overflow: 'hidden',
            border: 'none',
            boxShadow: '0 20px 40px rgba(0,0,0,0.1)',
            background: 'rgba(255,255,255,0.95)',
            backdropFilter: 'blur(20px)'
          }}
          bodyStyle={{ padding: '24px' }}
        >
          {loading ? (
            <div style={{ textAlign: 'center', padding: '80px 0' }}>
              <Spin size="large" tip="加载中..." />
            </div>
          ) : (
            <Table 
              rowKey="id" 
              dataSource={dataSource} 
              columns={cols} 
              pagination={{ 
                pageSize: 10, 
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }}
              scroll={{ x: 800 }}
              style={{
                '& .ant-table-thead > tr > th': {
                  background: 'linear-gradient(135deg, #f8f9ff, #f0f2ff)',
                  borderBottom: '2px solid #e6f0ff',
                  color: '#2c3e50',
                  fontWeight: '600'
                }
              }}
            />
          )}
        </Card>

        {/* 详情弹窗 */}
        <Modal
          visible={detailVisible}
          footer={null}
          onCancel={() => setDetailVisible(false)}
          title={
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              <div style={{
                width: '32px',
                height: '32px',
                borderRadius: '8px',
                background: 'linear-gradient(135deg, #667eea, #764ba2)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#fff'
              }}>
                <InfoCircleOutlined style={{ fontSize: '16px' }} />
              </div>
              <span style={{ fontSize: '18px', fontWeight: '600' }}>风险评估详情</span>
            </div>
          }
          width={700}
          style={{
            '& .ant-modal-content': {
              borderRadius: '20px',
              overflow: 'hidden'
            }
          }}
        >
          <div style={{
            background: 'linear-gradient(135deg, #f8f9ff, #f0f2ff)',
            padding: '20px',
            borderRadius: '12px',
            marginBottom: '24px'
          }}>
            <Typography.Paragraph style={{ margin: 0, color: '#667eea' }}>
              <strong>风险评分说明：</strong>此处的风险评分基于以下四个要素综合计算：
              <ul style={{ marginTop: '12px', paddingLeft: '20px' }}>
                <li>振幅因子：当日价格振幅（振幅越大风险越高）</li>
                <li>换手率因子：交易活跃度（换手率越高风险越高）</li>
                <li>仓位占比因子：该股票在您组合中的市值占比（越大越敏感）</li>
                <li>用户风险容忍度：您的问卷偏好决定了可接受的风险水平</li>
              </ul>
            </Typography.Paragraph>
          </div>
          
          {detail && (
            <Descriptions 
              column={1} 
              bordered
              style={{
                '& .ant-descriptions-item-label': {
                  background: 'linear-gradient(135deg, #f8f9ff, #f0f2ff)',
                  color: '#2c3e50',
                  fontWeight: '600'
                },
                '& .ant-descriptions-item-content': {
                  background: '#fff'
                }
              }}
            >
              <Descriptions.Item label="资产 ID">{detail.id}</Descriptions.Item>
              <Descriptions.Item label="产品代码">
                <Text strong style={{ color: '#3742fa' }}>{detail.products_id}</Text>
              </Descriptions.Item>
              <Descriptions.Item label="产品名称">
                <Text strong>{detail.products_name}</Text>
              </Descriptions.Item>
              <Descriptions.Item label="最新价格">
                <Text strong style={{ color: '#2ed573' }}>¥{detail.latest_price}</Text>
              </Descriptions.Item>
              <Descriptions.Item label="持仓数量">{detail.quantity}</Descriptions.Item>
              <Descriptions.Item label="买入价格">¥{detail.buy_price}</Descriptions.Item>
              <Descriptions.Item label="仓位市值">
                <Text strong style={{ color: '#2ed573' }}>
                  ¥{(detail.quantity * detail.latest_price).toLocaleString()}
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="振幅因子">
                <Text style={{ color: '#ffa502' }}>
                  {(detail.factors['振幅因子']*100).toFixed(2)}%
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="换手率因子">
                <Text style={{ color: '#ff9f43' }}>
                  {(detail.factors['换手率因子']*100).toFixed(2)}%
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="仓位占比因子">
                <Text style={{ color: '#26d0ce' }}>
                  {(detail.factors['仓位占比因子']*100).toFixed(2)}%
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="用户风险容忍度">
                <Text style={{ color: '#3742fa' }}>
                  {(detail.factors['用户风险容忍度']*100).toFixed(2)}%
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="综合匹配评分">
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                  <div 
                    style={{
                      width: '80px',
                      height: '8px',
                      borderRadius: '4px',
                      background: detail.risk_score > 0.7 ? 'linear-gradient(90deg, #ff4757, #ff6b7a)' : 
                                 detail.risk_score > 0.4 ? 'linear-gradient(90deg, #ffa502, #ffb74d)' : 
                                 'linear-gradient(90deg, #26d0ce, #4ecdc4)',
                      position: 'relative'
                    }}
                  >
                    <div 
                      style={{
                        position: 'absolute',
                        left: `${detail.risk_score * 100}%`,
                        top: '50%',
                        transform: 'translate(-50%, -50%)',
                        width: '3px',
                        height: '12px',
                        background: '#fff',
                        borderRadius: '2px',
                        boxShadow: '0 2px 4px rgba(0,0,0,0.3)'
                      }}
                    />
                  </div>
                  <Text strong style={{ 
                    color: detail.risk_score > 0.7 ? '#ff4757' : 
                           detail.risk_score > 0.4 ? '#ffa502' : '#26d0ce',
                    fontSize: '16px'
                  }}>
                    {(detail.risk_score * 100).toFixed(1)}%
                  </Text>
                </div>
              </Descriptions.Item>
            </Descriptions>
          )}
        </Modal>

         {/* ① 在页面最外层插入 ChatAssistant，设置为固定定位 */}
        
      </div>
      <ChatAssistant
        style={{
          position: 'fixed',
          bottom: '24px',
          right: '24px',
          zIndex: 1000
        }}
      />
    </div>
  );
};

export default RiskStock;